#include<unistd.h>
#include<iostream>
#include<pthread.h>
using namespace std;

//唯一的实例对象:T类型  单例类型:Singleton<T>
/*
template<class T>
class Singleton
{
public:
  static T* GetInstance()
  {
    if(inst == nullptr)
    {
      pthread_mutex_lock(&_mtx);
      if(inst == nullptr) //第一次调用GetInstance的时候才创建出唯一的T类型对象
         inst = new T();
      pthread_mutex_unlock(&_mtx);
    }
    
    cout << "inst address :" << inst << endl;
    return inst;
  }
private:
  static pthread_mutex_t _mtx;
  static T* inst; 
};
template<class T>
T* Singleton<T>::inst = nullptr;

template<class T>
pthread_mutex_t Singleton<T>::_mtx = PTHREAD_MUTEX_INITIALIZER; //静态初始化这个互斥锁
*/

//写法2:基于局部静态变量的懒汉模式
template<class T>
class Singleton
{
public:
  static T& GetInstance()
  {
    static T instance;
    return instance;
  }
private:
  Singleton()
  {}
  Singleton(const Singleton&) = delete;
  Singleton& operator=(const Singleton&) = delete;
};


// void* handle(void* arg)
// {
//   Singleton<int>* t = (Singleton<int>*)arg;
//   int count = 3;
//   while(count--) 
//   {
//     t->GetInstance();
//   }
//   return nullptr;
// }
int main()
{
  pthread_t tid[3];
  Singleton<int>* t = new Singleton<int>;
  for(int i = 0;i<3;i++)
  {
    pthread_create(&tid[i],NULL,handle,(void*)t); 
  }
  //线程等待
  for(int i = 0;i<3;i++)
    pthread_join(tid[i],nullptr);
  return 0;
}
